<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input :placeholder="$t('deal.id')" v-model="detailListQuery.id" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>

      <el-input :placeholder="$t('deal.idCard')" v-model="detailListQuery.baseid" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>


      <el-select v-model="detailListQuery.name" :placeholder="$t('table.vip')" clearable style="width: 90px" class="filter-item">
        <el-option v-for="isVip in isVips" :key="isVip" :label="isVip" :value="isVip"/>
      </el-select>


      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-edit" @click="delList">{{ $t('table.del') }}</el-button>

      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">{{ $t('table.export') }}</el-button>
    </div>


    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange">

      <el-table-column :label="$t('deal.baseid')" width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.baseid }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('deal.name')" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('deal.idCard')" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.idCard }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('deal.zfbId')" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.zfbId }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('deal.money')" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.money }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('deal.complaintNumber')" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.complaintNumber }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('deal.gender')" width="50px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.gender }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('deal.age')" width="50px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.age }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('deal.creationTime')" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.creationTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>


    </el-table>



    <pagination v-show="total>0" :total="total" :page.sync="detailListQuery.page" :limit.sync="detailListQuery.limit"
                @pagination="getList"/>





  </div>
</template>

<script>
  import { fetchList, fetchPv, createArticle, updateArticle } from '@/api/article'
  import waves from '@/directive/waves' // Waves directive
  import { parseTime } from '@/utils'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

  import { findALlDetailInfo } from '@/api/worker'


  export default {
    name: 'ComplexTable',
    components: { Pagination },
    directives: { waves },
    filters: {
      statusFilter(status) {
        const statusMap = {
          0: 'success',
          1: 'danger'
        }
        return statusMap[status]
      }
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        detailListQuery: {
          page: 1,
          limit: 10
        },
        isVips: [0, 1],
        textMap: {
          update: 'Edit',
          create: 'Create'
        },

        downloadLoading: false
      }
    },
    created() {
      //获取信息
      this.getList()
      //获取路径中的id
      this.getWorkerId()

    },


    methods: {

      //获取路径中的id
      getWorkerId(){
        if (this.$route.query.id){
          this.detailListQuery.id = this.$route.query.id
        };
      },
      //清空列表
      delList(){
        this.detailListQuery.id='',
          this.detailListQuery.mobile='',
          this.detailListQuery.isVip='',
          this.getList()
      },
      //查询列表
      getList() {
        this.listLoading = true
        findALlDetailInfo(this.detailListQuery).then(response => {
          this.list = response.data.data.list

          this.total = response.data.data.total


          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      },
      handleFilter() {
        this.detailListQuery.page = 1
        this.getList()
      },

      // 排序
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },

      sortByID(order) {
        if (order === 'ascending') {
          this.detailListQuery.sort = '+id'
        } else {
          this.detailListQuery.sort = '-id'
        }
        this.handleFilter()
      },

      resetTemp() {
        this.temp = {
          id: undefined,
          importance: 1,
          remark: '',
          timestamp: new Date(),
          title: '',
          status: 'published',
          type: ''
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
            this.temp.author = 'vue-element-admin'
            createArticle(this.temp).then(() => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },

      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            updateArticle(tempData).then(() => {
              for (const v of this.list) {
                if (v.id === this.temp.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.temp)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete(row) {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        const index = this.list.indexOf(row)
        this.list.splice(index, 1)
      },
      handleFetchPv(pv) {
        fetchPv(pv).then(response => {
          this.pvData = response.data.pvData
          this.dialogPvVisible = true
        })
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['ID', 'NiceName', 'Mobile', 'Openid', 'Vip', 'Date', 'Status']
          const filterVal = ['id','nickname', 'mobile', 'openid', 'isVip', 'creationTime', 'isFreeze']
          const data = this.formatJson(filterVal, this.list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'worker-list'
          })
          this.downloadLoading = false
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      }
    }
  }
</script>
